var BT,
    btAppSchema;
var page = {
    csrf: $('body').attr('data-csrf'),
    loading: $('#popup-loading'),
    currentPayment: '',
    wechatPaymentURL: '/tp/order/pay/wxpay/' + BT.context('groupOrderId') + '/',
    unipayPaymentURL: '/tp/order/pay/soopay/' + BT.context('groupOrderId') + '/',
    alipayPaymentURL: '/tp/order/pay/alipay/' + BT.context('groupOrderId') + '/',
    TIMER: '',
    callbackURL: '/tp/order/pay/callback/' + BT.context('groupOrderId') + '/view/',
    wxpayCallbackPopup: $('#wxpay-callback-popup'),
    init: function () {
        page.paymentEvents();
        page.countdownEvents();
        page.localStorageEvents();
        page.popupEvents();
        if (BT.context('callbackMsg') !== '') {
            alert(BT.context('callbackMsg'));
        }
    },
    paymentEvents: function () {
        var $tr = $('#payment tr');

        if ($tr.length > 0) {
            $tr.on('click', page.selectPayment);
            $tr.first().trigger('click'); // 默认选择第一个支付方式
        }

        $('#btn-pay').on('click', page.gotoPay);
    },
    popupEvents: function () {
        $('#popup-wxpay-close, #popup-repay-btn').on('click', function(e) {
            e.preventDefault();
            page.wxpayCallbackPopup.hide();
            $('body').off('touchmove', page.offMove);
        });

        $('#popup-complete-btn').on('click', function(e) {
            e.preventDefault();
            window.location.reload();
        });

        // $('#popup-repay-btn').on('click', page.gotoPay);
    },
    offMove: function (e) {
        e.preventDefault();
    },
    selectPayment: function () {
        var $this = $(this);
        $this.find('input').prop('checked', true);
        page.currentPayment = $this.attr('data-payment');
    },
    inApp: function () {
        // 判断是否在面包旅行 App 内

        if (btAppSchema.appVersion) {
            return true;
        } else {
            return false;
        }
    },
    gotoPay: function (e) {
        e.preventDefault();

        if ($(this).hasClass('btn-disable')) {
            // 支付超时
            alert('订单已过期，请重新预定');
            return false;
        }

        // 显示 loading
        if (!btAppSchema.appVersion) {
            page.loading.show();
        }

        switch (page.currentPayment) {
            case 'wechat':
                // iOS 微信回调有问题，暂时增加确认弹层
                if (btAppSchema.user_agent === 1 || btAppSchema.user_agent === 2) {
                    setTimeout(function() {
                        page.loading.hide();
                        page.wxpayCallbackPopup.show();
                        $('body').on('touchmove', page.offMove);
                    }, 7000);
                }

                if (page.inApp()) {
                    btAppSchema.jumpToWxpay(BT.context('groupOrderId'));
                } else {
                    page.wechatAppPay();
                }
            break;
            case 'alipay':
                btAppSchema.jumpToAlipay(BT.context('subject'), BT.context('subject'), BT.context('price'), BT.context('groupOrderId'));
            break;
            case 'unipay':
                window.location.href = page.unipayPaymentURL;
            break;
            case '': // 不需要支付
                page.paymentURL = '/tp/order/pay/' + BT.context('groupOrderId') + '/';
                window.location.href = page.paymentURL;
            break;
        }
    },
    wechatAppPay: function () {
        var params = {
            'csrfmiddlewaretoken': page.csrf,
            'code': BT.context('code'),
            },
            url = '/tp/order/pay/wechat_app/' + BT.context('groupOrderId') + '/';
        $.post(url, params, function(data) {
            if (typeof WeixinJSBridge == 'undefined'){

               if( document.addEventListener ){
                   document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
               }else if (document.attachEvent){
                   document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                   document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
               }

            }else{
               onBridgeReady(data);
            }
        });
    },
    refreshExpriedCounting: function () {
        window.clearTimeout(page.TIMER);
        var $countdown = $('#countdown'),
            $btnPay = $('#btn-pay'),
            time = $countdown.attr('data-time'),
            expired = new Date(parseInt(time, 10) * 1000), // 支付结束时间
            now = new Date(),
            delta = (expired - now) / 1000,
            minute = parseInt(delta / 60, 10) % 60,
            second = parseInt(delta % 60, 10) + '',
            hour = parseInt(delta / 3600, 10),
            countdownText = '';

        hour = hour < 10 ? '0' + hour : hour ;
        minute = minute < 10 ? '0' + minute : minute ;
        second = second < 10 ? '0' + second : second ;

        if(!$countdown){
            return;
        }

        if(expired < now) {
            // 支付过期
            $btnPay.addClass('btn-disable');
            countdownText = '00:00';
        }else{
            // 支付进行中
            if(hour != '00'){
                countdownText += hour + ':' + minute + ':' + second;
            } else if(minute){
                countdownText += minute + ':' + second;
            } else if(second){
                countdownText += '00:' + second;
            }
            page.TIMER = setTimeout(function(){
                page.refreshExpriedCounting();
            }, 250);
        }
        $countdown.find('span').html(countdownText);
        
    },
    countdownEvents: function () {
        page.refreshExpriedCounting();
    },
    localStorageEvents: function () {
    // 清除订单本地缓存
        var item = 'tp_' + BT.context('productId') + '_order';
        localStorage.removeItem(item);
    },
};

function onBridgeReady (data) {
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', data,
        function(res){
            if (res.err_msg.indexOf('ok') != -1) {
            // 支付成功

                window.location.reload();
            } else if (res.err_msg.indexOf('cancel') != -1) {
            // 取消支付

                page.loading.hide();
            } else if (res.err_msg.indexOf('fail') != -1) {
            // 支付失败

                page.loading.hide();
            }
        }
    );
}

btAppSchema.paymentRequestCallback = function (paymentName, success) {
    if (success) {
        btAppSchema.showNotification('正在跳转，请稍候');
    } else {
        page.loading.hide();
        // btAppSchema.showNotification('支付跳转：payment_name: '+ paymentName + ', success: ' + success );
    }
};

btAppSchema.paymentResponseCallback = function (paymentName, success) {
    if (success) {
        window.location.reload();
    } else {
        // btAppSchema.showNotification('支付结果：payment_name: '+ paymentName + ', success: ' + success );
    }
};

$(document).ready(function() {
    page.init();
});